<script setup>
import { find, includes, merge } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest, useWatch, useResetForm, useDownload } from '@/hooks';
import { usePickerOption } from '@/views/hooks';
import { useJCTrendChart } from '@/views/home/hooks.js';
import { useDSECTrend } from '@/views/orgMgmt/hooks.js';
import { getAreaList, getBuildingByArea } from '@/api/index.js';
import { TableList } from '@/components/MainComponents.js';
import CECharts from '@/components/chart/CECharts.vue';
import TreeSelect from '@/components/TreeSelect.vue';

const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: { type: 'year', fmt: 'yyyy', default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')] },
});
const queryForm = ref(null);
const cascader = ref(null);
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'areaName',
  value: 'areaName',
});
const activeName = ref('insTotalEC');
const initValue = {
  dateType: 'd',
  energyType: 0,
  projectType: 'JC',
  istco2e: false,
  dateStart: rangeType.value.d.default[0],
  dateEnd: rangeType.value.d.default[1],
};
const trInitValue = {
  energyType: '',
  buildingCode: null, //机构编码
  dateType: 'd', //时间类型，d-日，m-月。y-年
  sDate: rangeType.value.d.default[0], //开始时间
  eDate: rangeType.value.d.default[1], //结束时间
  equSysName: null, //设备系统名称
};
const columnObj = ref({
  index: true,
  columnData: [
    { text: true, prop: 'date', label: '统计时间' },
    { text: true, prop: 'energyType', label: '能源类型' },
    { text: true, prop: 'thisValue', label: '实际能耗量' },
    { text: true, prop: 'togetherValue', label: '同比(%)' },
    { text: true, prop: 'chainValue', label: '环比(%)' },
  ],
});
const columnObj2 = ref({
  index: true,
  columnData: [
    { text: true, prop: 'date', label: '统计时间' },
    { text: true, prop: 'equSysName', label: '设备系统名称' },
    { text: true, prop: 'energyType', label: '能源类型' },
    { text: true, prop: 'thisValue', label: '实际能耗量' },
    { text: true, prop: 'togetherValue', label: '同比(%)' },
    { text: true, prop: 'chainValue', label: '环比(%)' },
  ],
});

const [
  dateRangeEC,
  dateRangeCE,
  yearRangeEC,
  yearRangeCE,
  lineExtraOpts1,
  lineExtraOpts2,
  ECParams,
  CEParams,
  ECLoading,
  CELoading,
  engTypeList,
  engTypeList2,
  changeType,
  handleECBuildingCode,
  handleCEBuildingCode,
  handleECDaterange,
  handleCEDaterange,
  handleECYearrange,
  handleCEYearrange,
] = useJCTrendChart(rangeType, false);

const [
  trendParams,
  dSysList,
  lineExtraOpts,
  dateRangeTr,
  yearRangeTr,
  trendLoading,
  ,
  handleTrDaterange,
  handleTrYearrange,
  handleSysName,
] = useDSECTrend(rangeType);

const cascaderChange = bool => {
  if (!bool) {
    insParams.value.areaName = cascader.value.join('/');
    runIns(insParams.value);
  }
};

const handleInId = val => {
  handleECBuildingCode(val);
  trendParams.value.buildingCode = val;
};
const handleQuery = () => {};
const resetQuery = async () => {
  await runArea({});
  ECParams.value = merge(ECParams.value, initValue);
  trendParams.value = merge(trendParams.value, trInitValue);
};
const handleExport = () => {
  useDownload('/energyservice/NewOverviewController/getDateCoalValueExcel', ECParams.value);
};
const handleExport2 = () => {
  useDownload('/energyservice/euqSys/getEquSysReportsExport', trendParams.value);
};

const insParams = ref({
  isStage: '1',
  areaName: null,
  projectType: 'JC',
});
const [areaList, , runArea] = useRequest(getAreaList, {
  defaultParams: [{}],
  onSuccess: res => {
    cascader.value = res.data?.[0]?.areaName ?? null;
    insParams.value.areaName = cascader.value;
    runIns(insParams.value);
  },
});
const [institutionList, , runIns] = useRequest(getBuildingByArea, {
  defaultParams: [{}],
  manual: true,
  onSuccess: res => {
    const selInId = find(res.data, v => includes(['JCOPERATION', 'OPERATION'], v.entrustStage))?.enterpriseCode ?? null;
    ECParams.value.inId = selInId;
    trendParams.value.buildingCode = selInId;
    handleECBuildingCode(ECParams.value.inId);
  },
});

const disabledDateStartEC = ref({
  disabledDate: time => {
    if (yearRangeEC.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeEC.value.eYear) || dayjs(time) < dayjs(yearRangeEC.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateEC = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeEC.value.sYear) || dayjs(time) > dayjs(yearRangeEC.value.sYear).add(2, 'year');
  },
});
const disabledDateTr = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeTr.value.sYear) || dayjs(time) > dayjs(yearRangeTr.value.sYear).add(2, 'year');
  },
});
const disabledDateStartTr = ref({
  disabledDate: time => {
    if (yearRangeTr.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeTr.value.eYear) || dayjs(time) < dayjs(yearRangeTr.value.eYear).subtract(2, 'year')
      );
    }
  },
});
</script>

<template>
  <div class="app-container">
    <el-form ref="queryForm" inline class="u-base-fg u-p20 u-mb20">
      <el-form-item label="行政区划">
        <el-cascader
          v-model="cascader"
          :props="cascaderProps"
          :options="areaList"
          placeholder="请选择行政区划"
          size="small"
          clearable
          @visible-change="cascaderChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="机构名称">
        <el-select v-model="ECParams.inId" placeholder="请输入机构名称" filterable size="small" @change="handleInId">
          <el-option
            v-for="(val, index) in institutionList"
            :key="`${val.enterpriseCode}-${index}`"
            :label="val.enterpriseName"
            :value="val.enterpriseCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button type="primary" size="small" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="u-base-fg u-p20 u-pt7 insHeight">
      <el-tabs v-model="activeName">
        <el-tab-pane label="机构总能耗" name="insTotalEC">
          <el-form :model="ECParams" :inline="true" class="u-df-ed">
            <el-form-item prop="energyType" class="u-mr10">
              <el-select v-model="ECParams.energyType" placeholder="" size="mini" class="u-mr10">
                <el-option
                  v-for="item in engTypeList"
                  :key="item.id"
                  :label="item.energyName + '能耗'"
                  :value="item.id"
                  @click.native="changeType(item)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="rangeType[ECParams.dateType].type !== 'year'">
              <el-date-picker
                v-model="dateRangeEC"
                :type="rangeType[ECParams.dateType].type ?? 'daterange'"
                :key="rangeType[ECParams.dateType].type ?? 'daterange'"
                :value-format="rangeType[ECParams.dateType].fmt ?? 'yyyy-MM-dd'"
                :picker-options="rangeType[ECParams.dateType].pickerOptions"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                align="left"
                class="u-mr10"
                style="width: 240px"
                @change="handleECDaterange"
              />
            </el-form-item>
            <el-form-item v-else>
              <el-date-picker
                v-model="yearRangeEC.sYear"
                :picker-options="disabledDateStartEC"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="开始年份"
                size="mini"
                style="width: 115px"
                class="u-mr5"
                @change="handleECYearrange"
              />
              <el-date-picker
                v-model="yearRangeEC.eYear"
                :picker-options="disabledDateEC"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="结束年份"
                size="mini"
                class="u-mr10"
                style="width: 115px"
                @change="handleECYearrange"
              />
            </el-form-item>
            <el-form-item prop="dateType" style="margin-right: 0 !important">
              <el-radio-group v-model="ECParams.dateType" size="mini">
                <el-radio-button label="d">日</el-radio-button>
                <el-radio-button label="m">月</el-radio-button>
                <el-radio-button label="y">年</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <CECharts
            v-if="activeName === 'insTotalEC'"
            v-loading="ECLoading"
            :options="lineExtraOpts1"
            type="line"
            style="height: 300px"
          />
          <div class="u-df-ed u-mt20 u-mb20">
            <el-button type="primary" size="small" plain @click="handleExport">导出报表</el-button>
          </div>
          <TableList :tableData="lineExtraOpts1?.dataset.source ?? []" :columObj="columnObj" :height="500"></TableList>
        </el-tab-pane>
        <el-tab-pane label="设备系统能耗" name="devSysEC">
          <el-form :model="trendParams" :inline="true" class="u-df-spb">
            <el-form-item prop="energyType" class="u-mr10">
              <TreeSelect
                v-model="trendParams.equSysName"
                :data="dSysList ?? []"
                placeholder="请选择设备系统"
                size="mini"
                style="width: 240px"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-form-item v-if="rangeType[trendParams.dateType].type !== 'year'">
                <el-date-picker
                  v-model="dateRangeTr"
                  :type="rangeType[trendParams.dateType].type ?? 'daterange'"
                  :key="rangeType[trendParams.dateType].type ?? 'daterange'"
                  :value-format="rangeType[trendParams.dateType].fmt ?? 'yyyy-MM-dd'"
                  :picker-options="rangeType[trendParams.dateType].pickerOptions"
                  :clearable="false"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="mini"
                  align="left"
                  style="width: 240px"
                  @change="handleTrDaterange"
                />
              </el-form-item>
              <el-form-item v-else>
                <el-date-picker
                  v-model="yearRangeTr.sYear"
                  :picker-options="disabledDateStartTr"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="开始年份"
                  size="mini"
                  style="width: 115px"
                  class="u-mr5"
                  @change="handleTrYearrange"
                />
                <el-date-picker
                  v-model="yearRangeTr.eYear"
                  :picker-options="disabledDateTr"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="结束年份"
                  size="mini"
                  style="width: 115px"
                  @change="handleTrYearrange"
                />
              </el-form-item>
              <el-form-item prop="dateType" class="u-df-ct">
                <el-radio-group v-model="trendParams.dateType" size="mini">
                  <el-radio-button label="d">日</el-radio-button>
                  <el-radio-button label="m">月</el-radio-button>
                  <el-radio-button label="y">年</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-form-item>
          </el-form>
          <CECharts
            v-if="activeName === 'devSysEC'"
            v-loading="trendLoading"
            :options="lineExtraOpts"
            type="line"
            style="height: 300px"
          />
          <div class="u-df-ed u-mt20 u-mb20">
            <el-button type="primary" size="small" plain @click="handleExport2">导出报表</el-button>
          </div>
          <TableList :tableData="lineExtraOpts?.dataset.source ?? []" :columObj="columnObj2" :height="500"></TableList>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.insHeight {
  height: calc(100% - 100px);
  overflow-y: auto;
}
.u-pt7 {
  padding-top: 7px;
}
:deep(.el-form-item) {
  margin-bottom: 0;
  .el-form-item__content {
    height: 40px;
    line-height: 40px;
  }
}
</style>
